package com.example.rpc.framework.protocl.http;

import com.alibaba.fastjson.JSONObject;
import com.example.rpc.framework.Invocation;
import com.example.rpc.framework.registry.LocalRegister;
import org.apache.commons.io.IOUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HttpServletHandler {
    public void handler(HttpServletRequest req, HttpServletResponse rep) throws IOException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //处理请求逻辑，接受到请求
        //解析请求-->调用服务--->服务类，方法名，服务参数列表，参数
        //解析请求，要进行反序列化，可以采用新能比较差的jdk序列化，这里采用json方式
        Invocation invocation = JSONObject.parseObject(req.getInputStream(), Invocation.class);

        String interfaceName=invocation.getInterfaceName();//
        String methodName=invocation.getMethodName();
        Class[] paramType=invocation.getParamType();
        Object[] param=invocation.getParams();

        //如何找到实现类-->本地注册--->服务启动的时候，要进行本地注册
        Class impl=LocalRegister.get(interfaceName);
        Method method=impl.getMethod(methodName,paramType);
        String result=(String)method.invoke(impl.newInstance(),param);

        //返回结果
        IOUtils.write(result,rep.getOutputStream());
    }
}